import Taro, {useState, useEffect, useCallback, useRef} from '@tarojs/taro'
import {View, Text, Image, Icon, Canvas, ScrollView, Video} from '@tarojs/components'
import {AtIcon, AtTextarea} from 'taro-ui'
import './index.scss'
import {getGlobalData} from '../../utils/global'
import lovelornUser, {MarriageSeekingMessageVO} from '../../api/lovelorn-user'
import env from '../../utils/env.json'
import ScaleImg from '../../components/ScaleImg'

const uploadFile = require('../../utils/upload')

function Desquamation() {
  const [infoTxt, setInfoTxt] = useState('')
  const [voice, setVoice] = useState({})
  const [fileImg, setFileImg] = useState([] as string[])
  const [isHide, setIsHide] = useState(false)
  const [isShow, setIsShow] = useState(false)
  const [marriageSeekingUser, setmarriageSeekingUser] = useState({} as MarriageSeekingMessageVO)
  const [expandFlag, setexpandFlag] = useState(false)
  const [recordStatus, setRecordStatus] = useState(false)
  let [count, setCount] = useState(0)
  const [voiceList, setVoiceList] = useState([])
  const timer = useRef(null)
  const [premissionStatus, setPremissionStatus] = useState(1)
  const recorderManager = useRef(null)
  const innerAudioContext = useRef(null)
  const [mediaUrl, setMediaUrl] = useState([])
  const [imageArray, setImageArray] = useState([])
  const [successResult, setSuccessResult] = useState(false)
  const selectType = useRef(null)

  const [userInfo, setUserInfo] = useState(getGlobalData('loginVO') ? getGlobalData('loginVO') : {})

  const getSeekingInfo = async () => {
    try {
      let res = await lovelornUser.marriageSeekingMessages.msgShare({
        marriageSeekingKid: this.$router.params.toUserId,
      })
      console.log(res, 'res')
      setmarriageSeekingUser(res)
    } catch (ex) {
      console.log(ex, 'ex')
    }
  }
  useEffect(() => {
    getSeekingInfo()
  }, [])
  // 开始录音
  const record = () => {
    if (premissionStatus == 2) {
      // 授权成功
      recorderManager.current = Taro.getRecorderManager()
      const options = {
        duration: 60000, // 指定录音的时长，单位 ms
        sampleRate: 16000, // 采样率
        numberOfChannels: 1, // 录音通道数
        encodeBitRate: 96000, // 编码码率
        format: 'mp3', // 音频格式，有效值 aac/mp3
        frameSize: 50, // 指定帧大小，单位 KB
      }
      recorderManager.current.start(options)
      recorderManager.current.onStart(() => {
        console.log('recorder start')
      })
      recorderManager.current.onError(ex => {
        console.log(ex)
      })
    } else {
      Taro.openSetting({
        success: function(res) {
          console.log(res, 'wadd')
          if (res.authSetting) {
            if (res.authSetting['scope.record'] == true) {
              setPremissionStatus(2)
            }
          } else {
            Taro.showToast({
              title: '获取用户权限失败',
              icon: 'none',
            })
          }
        },
      })
    }
  }
  // 停止录音
  const stopRecord = () => {
    let currentRecord = {}
    console.log('停止录音', recorderManager)
    recorderManager.current.stop()
    recorderManager.current.onStop(res => {
      console.log(res, '停止录音')
      currentRecord.duration = res.duration
      currentRecord.isPlaying = false
      // setVoiceList([...voiceList, res])
      uploadFile({
        filePath: res.tempFilePath,
        dir: 'mallMiniprogram',
        success: function(result) {
          console.log('上传成功')
          console.log(result, 'res')
          currentRecord.tempFilePath = result
          setMediaUrl([...mediaUrl, result])
          setVoiceList([...voiceList, currentRecord])
          Taro.hideLoading()
        },
        fail: function(ex) {
          console.log('上传失败')
          console.log(ex)
        },
      })
    })

    recorderManager.current.onError(ex => {
      console.log(ex, 'stop')
    })
  }
  const progress_canvas = step => {
    // 使用 wx.createContext 获取绘图上下文 context
    const context = Taro.createCanvasContext('progress_canvas')
    const grd = context.createLinearGradient(0, 0, 200, 0)
    grd.addColorStop(0, '#FE967F')
    grd.addColorStop(1, '#FF5414')
    context.setLineWidth(3)
    context.setStrokeStyle(grd)
    context.setLineCap('round')
    context.beginPath()
    context.arc(35, 35, 33, -Math.PI / 2, step * Math.PI - Math.PI / 2, false)
    context.stroke()
    context.draw()
  }
  // 绘制录音进度
  const countInterval = () => {
    if (timer.current) {
      clearInterval(timer.current)
    }
    timer.current = setInterval(() => {
      if (count <= 60) {
        progress_canvas(count / (60 / 2))
        setCount(() => {
          return (count += 1)
        })
      } else {
        console.log('60s倒计时完成')
        clearInterval(timer.current)
        stopRecord()
        setIsShow(false)
        setCount(0)
      }
    }, 1000)
  }

  useEffect(() => {
    Taro.getStorage({
      key: 'loginVO',
      success: function(res) {
        setUserInfo(res.data)
      },
    })
  }, [])

  //获取文本内容
  const handleChange = e => {
    setInfoTxt(e)
  }
  const getClose = () => {
    setIsHide(false)
    setIsShow(false)
  }
  const expand = useCallback(() => {
    setexpandFlag(!expandFlag)
  }, [expandFlag])
  useEffect(() => {
    // getPremission()
  }, [])
  // 获取录音权限
  const getPremission = () => {
    Taro.authorize({
      scope: 'scope.record',
      success() {
        console.log('录音授权成功')
        setPremissionStatus(2)
      },
      fail() {
        console.log('第一次录音授权失败')
        Taro.showModal({
          title: '提示',
          content: '您未授权录音，功能将无法使用',
          showCancel: true,
          confirmText: '授权',
          confirmColor: '#52a2d8',
          success: function(res) {
            if (res.confirm) {
              // 确认则打开设置页面（重点）
              Taro.openSetting({
                success: result => {
                  console.log(result.authSetting)
                  if (!result.authSetting['scope.record']) {
                    // 未设置录音授权
                    console.log('未设置录音授权')
                    Taro.showModal({
                      title: '提示',
                      content: '您未授权录音，功能将无法使用',
                      showCancel: false,
                      success: function(ex) {},
                    })
                  } else {
                    // 第二次才成功授权
                    console.log('设置录音授权成功')
                    setPremissionStatus(2)
                  }
                },
                fail: function() {
                  console.log('授权设置录音失败')
                },
              })
            } else if (res.cancel) {
              console.log('cancel')
            }
          },
          fail: function() {
            console.log('openfail')
            Taro.openSetting({
              success: function(res) {
                console.log(res, 'wadd')
                if (res.authSetting) {
                  if (res.authSetting['scope.record'] == true) {
                    setPremissionStatus(2)
                  }
                } else {
                  Taro.showToast({
                    title: '获取用户权限失败',
                    icon: 'none',
                  })
                }
              },
            })
          },
        })
      },
    })
  }
  // 录音操作
  const recordOper = useCallback(
    e => {
      console.log('aaaa', e, recordStatus)
      if (!recordStatus) {
        console.log('recording')
        countInterval()
        record()
      } else {
        clearInterval(timer.current)
        stopRecord()
        setIsShow(false)
        setCount(0)
      }
      setRecordStatus(() => {
        return !recordStatus
      })
      // recordStatus.current = !recordStatus.current
    },
    [recordStatus, isShow],
  )

  const playVoice = el => {
    innerAudioContext.current = Taro.createInnerAudioContext()
    innerAudioContext.current.autoplay = true
    innerAudioContext.current.src = el.tempFilePath

    innerAudioContext.current.onPlay(() => {
      console.log('开始播放')
      voiceList.map((item, index) => {
        item.isPlaying = false
        if (item.tempFilePath == el.tempFilePath) {
          voiceList[index].isPlaying = true
        }
      })
      setVoiceList([...voiceList])
    })
    innerAudioContext.current.onEnded(() => {
      console.log('播放结束', voiceList)
      voiceList.map((item, index) => {
        if (item.tempFilePath == el.tempFilePath) {
          voiceList[index].isPlaying = false
        }
      })
      setVoiceList([...voiceList])
    })

    innerAudioContext.current.onError(res => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  }

  const chooseImage = () => {
    let totalCount = 0
    let speed = 0
    let mediaArray = []
    setIsHide(false)
    selectType.current = 'image'
    Taro.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        if (tempFilePaths.length + fileImg.length > 9) {
          Taro.showToast({
            title: '上传图片最多不超过九张',
            icon: 'none',
          })
          return
        }
        Taro.showLoading({
          title: '上传中',
          mask: true,
        })

        console.log(tempFilePaths, 'tempFilePaths')
        setFileImg([...fileImg, ...tempFilePaths])
        totalCount = tempFilePaths.length

        tempFilePaths.forEach((el, index) => {
          Taro.uploadFile({
            url: `${env.httpBaseUrl}/platform-support/v1.4/pt/uploads/action/upload-image`,
            filePath: tempFilePaths[index],
            name: 'file',
            header: {
              tenantId: 'lovelorn',
              devType: 4,
              userId: userInfo && userInfo.user && userInfo.user.userId,
              token: userInfo && userInfo.authInfo && userInfo.authInfo.token,
            },
            success: function(result) {
              console.log(result, 'resukt')
              if (JSON.parse(result.data).code == 200) {
                const resourceUrl = JSON.parse(result.data).data.resourceUrl
                mediaArray.push(resourceUrl)
                setMediaUrl([...mediaUrl, ...mediaArray])
              } else {
                Taro.showToast({
                  title: JSON.parse(result.data).msg,
                  icon: 'none',
                })
                setMediaUrl([...mediaUrl])
              }
            },
            fail: function(ex) {
              console.log(ex)
              Taro.showToast({
                icon: 'none',
                title: '图片上传失败',
              })
            },
            complete(result) {
              speed++
              if (speed == totalCount) {
                console.log('所有图片上传完成')
                Taro.hideLoading()
                console.log(fileImg)
              }
            },
          })
        })
      },
    })
  }

  const chooseVideo = () => {
    setIsHide(false)
    let mediaArray = []
    console.log('上传视频')
    selectType.current = 'video'

    Taro.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function(res) {
        Taro.showLoading({
          title: '上传中',
          mask: true,
        })
        uploadFile({
          filePath: res.tempFilePath,
          dir: 'mallMiniprogram',
          success: function(result) {
            console.log('上传成功')
            console.log(result, 'res')
            Taro.hideLoading()
            mediaArray.push(result)
            setMediaUrl([...mediaUrl, ...mediaArray])
            setFileImg([...fileImg, result])
          },
          fail: function(ex) {
            console.log('上传失败')
            console.log(ex)
          },
        })
      },
    })
  }

  const uploadSuccess = () => {
    Taro.navigateBack({
      delta: 1,
    })
  }

  const submitData = async () => {
    console.log(infoTxt)
    console.log(mediaUrl)
    if (!infoTxt || mediaUrl.length == 0) {
      Taro.showToast({
        title: '请完善提交信息',
        icon: 'none',
      })
      return false
    }

    try {
      let res = await lovelornUser.archiveInfo.createUserRequisitions({
        description: infoTxt,
        marriageSeekingId: this.$router.params.toUserId,
        mediaUrl: mediaUrl.join(','),
      })
      console.log(res)
      setSuccessResult(true)
    } catch (ex) {
      console.log(ex)
    }
  }
  const deletePic = (el, index) => {
    fileImg.splice(index, 1)
    if (fileImg.length == 0) {
      selectType.current = ''
    }
    setFileImg([...fileImg])
    mediaUrl.map((item, deleteIndex) => {
      if (item == el) {
        mediaUrl.splice(deleteIndex, 1)
        setMediaUrl([...mediaUrl])
      }
    })
  }

  const deleteVoice = (el, index) => {
    let status = false
    voiceList.map(item => {
      if (item.isPlaying) {
        status = true
        Taro.showToast({
          title: '请等待当前音频播放完毕',
          icon: 'none',
        })
        return
      }
    })
    if (!status) {
      voiceList.splice(index, 1)
      setVoiceList(() => {
        return voiceList
      })
      mediaUrl.map((item, deleteIndex) => {
        if (item == el.tempFilePath) {
          mediaUrl.splice(deleteIndex, 1)
          setMediaUrl([...mediaUrl])
        }
      })
    }
  }

  const viewPoster = el => {
    if (selectType.current == 'video') {
      setImageArray([el])
    } else {
      Taro.previewImage({
        current: el,
        urls: [el],
      })
    }
  }

  return (
    <View className="Desquamation">
      <View
        className={
          `${marriageSeekingUser.gender == 2}`
            ? 'Desquamation-top topBg2'
            : 'Desquamation-top topBg1'
        }>
        <View
          className={
            `${marriageSeekingUser.userPhoto}`
              ? 'at-row Desquamation-topTop'
              : 'at-row Desquamation-topTo2'
          }>
          <View className="at-col at-col-1 at-col--auto topTop-head">
            <Image className="head-img" src={marriageSeekingUser.userImg} />
            <View className="head-icon">征婚嘉宾</View>
          </View>
          <View className="at-col topTop-cent">
            <Text className="cent-txt">{marriageSeekingUser.seekingDescription}</Text>
            <Text className="cent-name">{marriageSeekingUser.nickName}</Text>
          </View>
          {marriageSeekingUser.userPhoto && (
            <Image className="topTop-right" src={marriageSeekingUser.userPhoto} />
          )}
        </View>
        <View className="Desquamation-topCent">
          <Text className={expandFlag ? 'toggleShow topCent-text' : 'toggleHide topCent-text'}>
            {marriageSeekingUser.seekingContent}
          </Text>
          <View className="topCent-Toggle" onClick={expand}>
            <Text className={expandFlag ? 'iconfont iconicon-up' : 'iconfont iconicon-down'}></Text>
            {expandFlag ? '收起' : '展开'}
          </View>
        </View>
      </View>

      <View className="Desquamation-cent">
        <View className="cent-topImg">提出你的脱单需求</View>
        {(isShow || successResult || imageArray.length > 0) && (
          <View className="fakeTextArea">提出你的脱单需求</View>
        )}
        {!isShow && !successResult && imageArray.length == 0 && imageArray.length == 0 && (
          <AtTextarea
            maxLength="360"
            placeholder="请在这里输入文字(您的个人信息我们将严格保密)"
            value={infoTxt}
            placeholderStyle="color:#899096"
            onChange={handleChange}></AtTextarea>
        )}

        <View className="cent-voice">
          <View className="voice-list">
            {voiceList.map((el, index) => {
              return (
                <View className="voice-listCent" key={`index${index}`}>
                  <View
                    className="at-row listCent-cent"
                    onClick={() => {
                      playVoice(el)
                    }}>
                    <View className="at-col at-col--auto listCent-txt">语音-{index + 1}</View>
                    <View className="at-col listCent-btn">
                      {parseInt(el.duration / 1000)}''
                      <View className="playOrPaused">
                        {!el.isPlaying && <Text className="iconfont iconplay"></Text>}
                        {el.isPlaying && <Text className="iconfont iconpause1"></Text>}
                      </View>
                    </View>
                  </View>
                  {/* <Icon size="20" type="clear" className="listCent-close" /> */}
                  <View
                    className="voice-delete"
                    onClick={() => {
                      deleteVoice(el, index)
                    }}>
                    <Text className="iconfont icondel"></Text>
                  </View>
                </View>
              )
            })}
            {/*  */}
          </View>
          <View
            className="voice-btn"
            onClick={() => {
              Taro.authorize({
                scope: 'scope.record',
                success() {
                  console.log('录音授权成功')
                  setPremissionStatus(2)
                  setIsShow(true)
                },
                fail() {
                  Taro.showModal({
                    title: '提示',
                    content: '您未授权录音，功能将无法使用',
                    showCancel: true,
                    confirmText: '授权',
                    confirmColor: '#52a2d8',
                    success: function(res) {
                      if (res.confirm) {
                        // 确认则打开设置页面（重点）
                        Taro.openSetting({
                          success: res => {
                            console.log(res.authSetting)
                            if (!res.authSetting['scope.record']) {
                              // 未设置录音授权
                              console.log('未设置录音授权')
                              Taro.showModal({
                                title: '提示',
                                content: '您未授权录音，功能将无法使用',
                                showCancel: false,
                                success: function(res) {},
                              })
                            } else {
                              // 第二次才成功授权
                              console.log('设置录音授权成功')
                              setPremissionStatus(2)
                            }
                          },
                          fail: function() {
                            console.log('授权设置录音失败')
                          },
                        })
                      } else if (res.cancel) {
                        console.log('cancel')
                      }
                    },
                    fail: function() {
                      console.log('openfail')
                      Taro.openSetting({
                        success: function(res) {
                          console.log(res, 'wadd')
                          if (res.authSetting) {
                            if (res.authSetting['scope.record'] == true) {
                              setPremissionStatus(2)
                            }
                          } else {
                            Taro.showToast({
                              title: '获取用户权限失败',
                              icon: 'none',
                            })
                          }
                        },
                      })
                    },
                  })
                },
              })
            }}>
            <Icon className="voice-btnIcon"></Icon>
            <Text className="voice-btnTxt">可用语音发送需求</Text>
          </View>
        </View>
      </View>
      <View className="Desquamation-footer">
        <Text className="footer-text">上传图片或视频</Text>
        <View className="footer-upload">
          <View className="at-row at-row--wrap">
            {fileImg.length &&
              fileImg.map((el, index) => {
                return (
                  <View className="at-col at-col-3" key={`index${index}`}>
                    <Icon
                      size="18"
                      type="clear"
                      className="file-imgClose"
                      onClick={() => {
                        deletePic(el, index)
                      }}
                    />
                    <View
                      className="file-img"
                      onClick={() => {
                        viewPoster(el)
                      }}>
                      {selectType.current == 'image' && (
                        <Image className="file-list-img" src={el} />
                      )}
                      {selectType.current == 'video' && (
                        <Video
                          objectFit="fill"
                          controls={false}
                          showCenterPlayBtn={false}
                          showFullscreenBtn={false}
                          className="file-list-video"
                          src={el}>
                          <Text className="iconfont iconpause"></Text>
                        </Video>
                      )}
                    </View>
                  </View>
                )
              })}
            {((fileImg.length == 0 && !selectType.current) ||
              (fileImg.length < 9 && selectType.current == 'image') ||
              (fileImg.length < 1 && selectType.current == 'video')) && (
              <View
                className="at-col at-col-3"
                onClick={() => {
                  if (selectType.current == 'image') {
                    chooseImage()
                  } else if (selectType.current == 'video') {
                    chooseVideo()
                  } else {
                    setIsHide(true)
                  }
                }}>
                 
                <View className="file-icon">
                                    <Text className="iconfont iconpic1"></Text>
                                    <View>上传</View>
                </View>
              </View>
            )}
          </View>
        </View>
      </View>
      <View className="Desquamation-btn" onClick={submitData}>
        提交需求
      </View>

      {isShow || isHide ? <View className="Desquamation-box" onClick={getClose}></View> : ''}

      {isHide && (
        <View className="Desquamation-boxCent">
          <Text onClick={chooseVideo}>视频</Text>
          <Text onClick={chooseImage}>图片</Text>
        </View>
      )}
      {/* <Icon   */}
      {isShow && (
        <View className="Desquamation-voice">
          <AtIcon
            size="20"
            value="close"
            color="#000"
            className="voice-close"
            onClick={() => {
              setIsShow(false)
              setCount(0)
            }}></AtIcon>
          <View className="voice-icon" onClick={recordOper}>
            {!recordStatus && (
              <Image
                className="voice-icon-img"
                src={require('../../assets/Desquamation-voice1.png')}
              />
            )}
            {recordStatus && (
              <Image
                className="voice-icon-img"
                src={require('../../assets/Desquamation-voice.png')}
              />
            )}
            <Canvas
              canvasId="progress_canvas"
              className="canvas"
              style={{
                width: '70px',
                height: '70px',
                margin: '0 auto',
                borderRadius: '50%',
              }}></Canvas>
          </View>

          <Text className="voice-text"> {recordStatus ? '点击结束说话' : '点击开始说话'}</Text>
        </View>
      )}
      {imageArray.length && (
        <View className="fullPage">
          {imageArray.map((el, index) => {
            return (
              <ScrollView scrollX className="full-img full-margin" key={`index${index}`}>
                {selectType.current == 'video' && (
                  <Video
                    onWaiting={() => {
                      console.log('加载中')
                    }}
                    className="full-video"
                    showFullscreenBtn={false}
                    objectFit="cover"
                    controls={false}
                    src={el}>
                    <Text
                      className="iconfont iconarrow-left"
                      onClick={() => {
                        setImageArray([])
                      }}></Text>
                  </Video>
                )}
                {/* {selectType.current == 'image' && (
                  <ScaleImg style={{width: '750px', overflow: 'scroll'}} src={el.image || el} />
                )} */}
              </ScrollView>
            )
          })}
          {selectType.current == 'image' && (
            <View
              className="full-Title"
              onClick={() => {
                setImageArray([])
              }}>
              <Text
                className="iconfont iconarrow-left "
                style={{position: 'absolute', left: '16px'}}>
                返回
              </Text>
            </View>
          )}
        </View>
      )}
      {successResult && (
        <View className="uploadResult">
          <View className="uploadInner">
            <Image
              className="uploadBanner"
              src={require('../../assets/seeking/commitSuccess.png')}
            />
            <View className="commitSuccess">提交成功</View>
            <View className="uploadResultTips">
              平台已收到您的需求，我们正在根据您的需求为您制定脱单方案,请留意查看“进度查询”页面
            </View>
            <View className="backBtn" onClick={uploadSuccess}>
              完成
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

export default Desquamation
